﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GridInfo : MonoBehaviour {

	// Use this for initialization
    public UnityEngine.UI.Text Mass;
    public UnityEngine.UI.Text Temperature;
    public UnityEngine.UI.Text GasPressure;
    public GameObject selecting;
//    public UnityEngine.UI.Button TestButton;


    public UnityEngine.UI.Button addbutton;
    public UnityEngine.UI.Button removebutton;

    public MatterView MassTemplete;
    static GridInfo _static;
    public static GridInfo Instance
    {
        get
        {
            return _static;
        }
    }

    void Awake()
    {
        _static = this;
        addbutton.onClick.AddListener(FullWithShiTou);
        removebutton.onClick.AddListener(Dig);
    }

    void Start ()
    {
		for(int i = 0; i < 20; i ++)
        {
            MatterView mv = GameObject.Instantiate(MassTemplete, MassTemplete.transform.parent);
            currentViews.Add(mv);
            mv.gameObject.SetActive(false);
        }
        StartCoroutine(Update1());
    }
	
	// Update is called once per frame
	IEnumerator Update1 () 
    {
        while(true)
        {
            yield return new WaitForSeconds(1.0f);
            SetInfo();
        }
    }

    void SetInfo()
    {
        if (_mg != null)
        {
            Mass.text = _mg.TotalMass.ToString("0.0") + "KG";
            Temperature.text = _mg.Temperature.ToString("0.0") + "℃";
            GasPressure.text = _mg.GasPressure.ToString("0.0") + "KPa";
            for (int i = 0; i < _mg.Matters.Count; i++)
            {
                currentViews[i].gameObject.SetActive(true);
                currentViews[i].SetMatter(_mg.Matters[i], _mg);
            }
            for (int i = _mg.Matters.Count; i < 20; i++)
            {
                currentViews[i].gameObject.SetActive(false);
            }
        }
    }
    MatterGrid _mg;

    public MatterGrid CurrentSelectGrid
    {
        get
        {
            return _mg;
        }
    }

    List<MatterView> currentViews = new List<MatterView>();
    public void SetMatterGrid(MatterGrid mg,Vector3 position)
    {
        if(_mg == mg)
        {
            return;
        }
        _mg = mg;
        SetInfo();
        selecting.transform.position = position;
    }

    public void Dig()
    {
        if(_mg != null)
        {
            if(!_mg.CannotDig)
            {
                MainGame.Instance.Scene.RemoveSolid(_mg.X, _mg.Y);
            }
        }
    }

    public void FullWithShiTou()
    {
        if (_mg != null)
        {
            if (!_mg.CannotDig)
            {
                MainGame.Instance.Scene.AddShiTou(_mg.X, _mg.Y);
            }
        }
    }
}
